// full_login_test.ts - 模拟完整的登录流程
import { verifyAdminCredentials, setAdminSessionCookie } from "./auth.ts";

async function simulateFullLoginFlow() {
  console.log("====== 完整登录流程模拟 ======");
  
  // 设置测试环境
  const username = "admin";
  const password = "password123";
  
  console.log(`登录凭据: ${username}/${password}`);
  
  // 1. 验证用户凭据
  console.log("\n1. 验证用户凭据");
  const authResult = await verifyAdminCredentials(username, password);
  
  if (!authResult.success) {
    console.error(`❌ 验证失败: ${authResult.errorType}`);
    return;
  }
  
  console.log("✅ 验证成功:", authResult);
  
  // 2. 创建和设置会话cookie
  console.log("\n2. 设置会话cookie");
  const headers = new Headers();
  
  await setAdminSessionCookie(
    headers,
    authResult.userId!,
    authResult.username!,
    authResult.displayName!,
    authResult.avatarUrl || null
  );
  
  const cookieHeader = headers.get("set-cookie");
  if (!cookieHeader) {
    console.error("❌ 无法设置cookie");
    return;
  }
  
  console.log("✅ Cookie已设置:", cookieHeader.substring(0, 50) + "...");
  
  // 3. 生成重定向URL
  console.log("\n3. 生成重定向URL");
  const originalUrl = new URL("http://localhost:8000/api/auth/login");
  const redirectUrl = new URL("/", originalUrl.origin);
  redirectUrl.searchParams.set("login_success", "true");
  
  console.log("✅ 重定向到:", redirectUrl.toString());
  
  // 模拟浏览器
  console.log("\n4. 浏览器收到响应");
  console.log("- 状态码: 303 (See Other)");
  console.log("- 重定向到:", redirectUrl.toString());
  console.log("- 设置Cookie:", cookieHeader.substring(0, 50) + "...");
  
  console.log("\n5. 浏览器发送后续请求");
  console.log("- URL:", redirectUrl.toString());
  console.log("- 附带Cookie:", `admin_session_token_v3=[cookie值]`);
  
  console.log("\n✅ 登录流程测试完成");
  console.log("如果实际登录过程中出现问题，很可能是网络、浏览器缓存或其他外部因素导致。");
  console.log("建议清除浏览器缓存和cookie，然后重试。");
}

// 运行测试
if (import.meta.main) {
  await simulateFullLoginFlow();
} 